<template>
  <div class="app-container home">
    <el-row :gutter="24">
      <el-col :sm="12" :lg="12">
        <el-card :header="$t('system_state')">
          <div class="cahrtBox">
            <pie id="cpuPie" :value="sysState.cpu" :title="$t('CPU_usage')" :width="200" :height="200"></pie>
            <pie id="memoryPie" :value="sysState.mem" :title="$t('memory_usage')" :width="200" :height="200"></pie>
            <temperature id="temperature" :value="sysState.temperature" :title="$t('core_temperature')" :width="200" :height="200">
            </temperature>
          </div>
        </el-card>
      </el-col>

      <el-col :sm="12" :lg="12">
        <el-card :header="$t('network_status')">
          <div class="cahrtBox">
            <netLine id="netLine" :value="netState" style="width: 100%; height: 220"></netLine>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="tabBox">
      <div class="tabBtn"><el-button type="primary" size="small" @click="toSetting">{{$t('setting')}}</el-button></div>
      <el-tabs v-if="showTab" v-model="activeName" type="border-card" style="margin-top:40px;position: relative;">
        <el-tab-pane :label="$t('lan1')" name="LAN1">
          <el-descriptions :column="3" border>
            <el-descriptions-item v-if="hardware.function.dhcp" label="DHCP">{{ netConfig.dhcp ?  $t('on') : $t('off')
            }}</el-descriptions-item>
            <el-descriptions-item label="IP">{{ netConfig.ip }}</el-descriptions-item>
            <el-descriptions-item :label="$t('mask')">{{ netConfig.mask }}</el-descriptions-item>
            <el-descriptions-item :label="$t('gateway')">{{ netConfig.gateway }}</el-descriptions-item>
            <el-descriptions-item label="DNS">{{ netConfig.dns }}</el-descriptions-item>
            <el-descriptions-item label="MAC">{{ mac }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane :label="$t('lan2')" name="LAN2" v-if="hardware.capability.eth1">
          <el-descriptions :column="3" border>
            <el-descriptions-item v-if="hardware.function.dhcp" label="DHCP">{{ netConfig2.dhcp ? $t('on') : $t('off')
            }}</el-descriptions-item>
            <el-descriptions-item label="IP">{{ netConfig2.ip }}</el-descriptions-item>
            <el-descriptions-item :label="$t('mask')">{{ netConfig2.mask }}</el-descriptions-item>
            <el-descriptions-item :label="$t('gateway')">{{ netConfig2.gateway }}</el-descriptions-item>
            <el-descriptions-item label="DNS">{{ netConfig2.dns }}</el-descriptions-item>
            <el-descriptions-item label="MAC">{{ mac2 }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane :label="$t('wifi')" name="WIFI" v-if="hardware.function.wifi">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="SSID">{{ wifiSsid }}</el-descriptions-item>
            <el-descriptions-item :label="$t('on')">{{ wifiConfig.enable ?  $t('yes') :  $t('no') }}</el-descriptions-item>
            <el-descriptions-item label="DHCP">{{ wifiConfig.DHCP }}</el-descriptions-item>
            <el-descriptions-item label="IP">{{ wifiConfig.ip }}</el-descriptions-item>
            <el-descriptions-item :label="$t('mask')">{{ wifiConfig.mask }}</el-descriptions-item>
            <el-descriptions-item :label="$t('gateway')">{{ wifiConfig.gateway }}</el-descriptions-item>
            <el-descriptions-item label="DNS">{{ wifiConfig.dns }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
    </div>




    <el-row :gutter="24" style="margin-top: 40px;">
      <el-col :sm="24" :lg="24">
        <el-card :header="$t('interface_state')">
          <div id="iface">
            <div v-for="item in inputState.hdmi" :class="`HDMI ${item.avalible ? '' : 'disable'}`"
              :title="item.protocol == 'HDMI' && item.avalible ? `${item.width}x${item.height}${item.interlace ? 'I' : 'P'}${item.framerate}` : ''">
              <span class="info">{{ item.avalible ? `${item.height}${item.interlace ? "I" : "P"}${item.framerate}` : '---'
              }}</span>
              <div class="bg"></div>
              <span class="name">{{ item.name }}</span>
            </div>
            <div v-for="item in inputState.sdi" :class="`SDI ${item.avalible ? '' : 'disable'}`">
              <span class="info">{{ item.avalible ? `${item.height}${item.interlace ? "I" : "P"}${item.framerate}` : '---'
              }}</span>
              <div class="bg"></div>
              <span class="name">{{ item.name }}</span>
            </div>
            <!-- <div class="AHD disable">
                <span class="info">- - -</span>
                <div class="bg"></div>
                <span class="name">item.name</span>
            </div> -->
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="24" style="margin-top: 40px;">
      <el-col :sm="24" :lg="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <div><span>{{ $t('preview') }}</span> <span style="color: #666;font-size: 14px;">{{ $t('video_preview_tip') }}</span></div>
              <el-switch v-model="previewState" @change="previewStateChange"></el-switch>
            </div>
          </template>
          <el-row :gutter="24" v-if="previewState">
            <el-col :xs="12" :sm="8" :md="6" v-for="item in previewList">
              <div class="thumbnail">
                <div style="min-height:20px"><img :src="item.src" @error="handleError"></div>
                <div id="L"
                  :style="{ 'width': (volList[item.index]?.L || 0) + '%', 'background-color': 'rgb(136, 187, 74)', 'height': '5px' }">
                </div>
                <div id="R"
                  :style="{ 'width': (volList[item.index]?.R || 0) + '%', 'background-color': 'rgb(136, 187, 74)', 'height': '5px' }">
                </div>
                <div class="caption text-center">{{ item.name }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index">
import pie from "@/components/Echarts/pie"
import temperature from "@/components/Echarts/temperature"
import netLine from "@/components/Echarts/netLine"
import RPC from "@/api/rpc"
import getJson from "@/api/getJson"
import Cookies from "js-cookie";
import nosignal from "@/assets/images/nosignal.jpg"
import errorImg from "@/assets/images/error-img.png"
const router = useRouter();

let hardware = reactive({})
let activeName = 'LAN1'
let showTab = ref(false)
let ifaceV = reactive({
  hdmi: [],
  sdi: []
})
getJson('/config/hardware.json').then(res => {
  hardware = reactive(res.data)
  showTab.value = true

  let arr = hardware.interfaceV;
  if (arr.length) {
    ifaceV.hdmi = arr.filter(item => item.type == 'HDMI')
    ifaceV.sdi = arr.filter(item => item.type != 'HDMI')
  }
})

let highUsage = false

// 系统状态
let sysState = reactive({
  cpu: 0,
  mem: 0,
  temperature: 0
})

function getSysState() {
  RPC('enc.getSysState').then(res => {
    let { cpu, mem, temperature } = res.data.result
    sysState.cpu = cpu
    sysState.mem = mem
    sysState.temperature = temperature

    if (cpu > 60 && !highUsage) {
      highUsage = true
      clearInterval(timerVol);
      clearInterval(timerSnap);
      timerVol = setInterval(getVolume, 1000);
      timerSnap = setInterval(show, 2000);
    }
  })
}
getSysState()
let getSysStateTimer = setInterval(getSysState, 3000)

// 网络状态
let netState = reactive({
  rx: new Array(50),
  tx: new Array(50)
})
function getNetState() {
  RPC('enc.getNetState').then(res => {
    let { rx, tx } = res.data.result
    netState.rx.shift()
    netState.tx.shift()
    netState.rx.push(rx)
    netState.tx.push(tx)
  })
}
getNetState()
let getNetStateTimer = setInterval(getNetState, 1000)

// 系统网络信息
// 网口1
let netConfig = ref({})
getJson("/config/net.json").then(res => {
  netConfig.value = res.data
})
let mac = ref('')
getJson("/config/mac").then(res => {
  mac.value = foramtMac(res.data)
})

// 网口2
let netConfig2 = ref({})
getJson("/config/net2.json").then(res => {
  netConfig2.value = res.data
})
let mac2 = ref('')
getJson("/config/mac2").then(res => {
  mac2.value = foramtMac(res.data)
})


// wifi
let wifiConfig = ref({})
getJson("/config/wifi.json").then(res => {
  wifiConfig.value = res.data
})
let wifiSsid = ref('')
getJson("/config/ssid.json").then(res => {
  wifiSsid.value = res.data.ssid
})

function foramtMac(str) {
  if (!str) return ''
  str = str.replace(/[\r\n]/g, "").toUpperCase()
  let result = ''
  for (var i = 0; i < str.length; i += 2) {
    result += str.substr(i, 2);
    if (i + 2 < str.length)
      result += ":";
  }
  return result;
}


// 接口状态
let inputState = reactive({
  hdmi: [],
  sdi: []
})
function getInputState() {
  RPC('enc.getInputState').then(res => {
    let arr = res.data.result
    if (arr.length) {
      let hdmiArr = arr.filter(item => item.protocol == 'HDMI')
      let sdiArr = arr.filter(item => item.protocol != 'HDMI')
      inputState.hdmi = hdmiArr.length ? hdmiArr : ifaceV.hdmi
      inputState.sdi = sdiArr.length ? sdiArr : ifaceV.sdi
    }
  })
}
getInputState()
let getInputStateTimer = setInterval(getInputState, 3000)

// 预览
let config = ref([])
let cnt = 0

let timerVol = null
let timerSnap = null

function startPreviewTimer() {
  stopPreviewTimer()
  timerSnap = setInterval(show, 1000);
  timerVol = setInterval(getVolume, 1000);
}

function stopPreviewTimer() {
  clearInterval(timerSnap)
  clearInterval(timerVol)
}

let previewState = ref(Cookies.get('preview') == 'false' ? false : true)

function previewStateChange(val) {
  Cookies.set('preview', val, { expires: 365 })
  if (!val) {
    stopPreviewTimer()
  } else {
    startPreviewTimer()
  }
}

getJson('/config/config.json').then(res => {
  config.value = res.data
  startPreviewTimer()
})


let previewList = ref([])
function show() {
  if (!previewState.value) return;
  RPC("enc.snap").then(res => {
    previewList.value = config.value.filter((item, index) => {
      if (!(!item.enable || (item.type == "net" && !item.net.decodeV))) {
        item.index = index
        item.src = item.enable ?
          `${import.meta.env.VITE_APP_HOST}/snap/snap${config.value[index].id}.jpg?rnd=${Math.random()}`
          : nosignal
        // item.src = nosignal
        return item
      }
    })
  })
}

let volList = ref([])
function getVolume() {
  if (!previewState.value) return;
  RPC("enc.getVolume").then(res => {
    volList.value = res.data.result
  })
}

function handleError(event) {
  var img = event.srcElement;
  if(errorImg){
    img.src = errorImg;
  }
}

function toSetting(){
  router.push({ path: '/setting/network' })
  
}

onBeforeUnmount(() => {
  clearInterval(getSysStateTimer)
  clearInterval(getNetStateTimer)
  clearInterval(getInputStateTimer)
  stopPreviewTimer()
});

</script>

<style scoped lang="scss">
.home {
  .cahrtBox {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  #iface {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #555;
    color: #ddd;
    text-align: center;
    border-radius: 4px;
    padding: 20px;

    &>div {
      height: 120px;
      margin: 0 30px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;

      .bg {
        background: url("@/assets/images/input.png") no-repeat;
      }

      &.disable {
        opacity: 0.3;
      }

      &.HDMI .bg {
        width: 68px;
        height: 26px;
        background-position: 0px -54px
      }

      &.SDI .bg {
        width: 45px;
        height: 54px;
        background-position: 0px 0px
      }

      &.AHD .bg {
        width: 102px;
        height: 37px;
        background-position: 0px -82px;
      }

      .info {
        text-align: center;
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .thumbnail {
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;

    img {
      display: block;
      max-width: 100%;
      height: auto;
      border: 1px solid #ddd
    }
  }

  .tabBox {
    position: relative;

    .tabBtn {
      position: absolute;
      top: 8px;
      right: 16px;
      z-index: 1
    }
  }

}
</style>

